package com.xand.jsonrpc;

import java.security.MessageDigest;


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;


public class JSONSerializer {
	private Gson gson;

	private Gson exposableGson;
	
	private String md5Secret;
	
	public JSONSerializer(String md5Secret) {
		this.md5Secret = md5Secret;
		
		gson = new GsonBuilder().create();
		exposableGson = new GsonBuilder()
		.excludeFieldsWithoutExposeAnnotation()
		.create();
	}

	public String serializeResponse(JSONGenericResponse res) throws Exception {
		String shortErrorMessage = res.getShortErrorMessage();
		String longErrorMessage = res.getLongErrorMessage();
		String responseCode = res.getResponseCode();

		res.setShortErrorMessage(null);
		res.setLongErrorMessage(null);
		res.setResponseCode(null);

		String data = gson.toJson(res);

		if(responseCode == null || responseCode.equals(""))
			responseCode = JSONGenericResponse.RESPONSE_OK;
				
		res.setShortErrorMessage(shortErrorMessage);
		res.setLongErrorMessage(longErrorMessage);
		res.setResponseCode(responseCode);
		
		res.setRes(data);

		return exposableGson.toJson(res);
	}

	public Object deserialize(String json, Class clazz) throws Exception {
		return gson.fromJson(json, clazz);
	}

	public String serializeRequest(JSONGenericRequest req) throws Exception {
		String serviceId = req.getServiceId();

		req.setServiceId(null);
		req.setMd5(null);

		String data = gson.toJson(req);

		req.setServiceId(serviceId);
		req.setReq(data);

		// calculo el md5 del data
		String md5 = md5((data + md5Secret).getBytes("UTF-8"));
		req.setMd5(md5);

		return exposableGson.toJson(req);
	}

	protected String md5(byte[] input) throws Exception {
		StringBuffer sb = new StringBuffer();
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		byte[] md5rslt = md5.digest(input);
		for (int i = 0; i < md5rslt.length; i++) {
			if (((int) md5rslt[i] & 0xff) < 0x10) { 
				sb.append("0");
			}
			sb.append(Integer.toHexString((0xff & md5rslt[i])));
		}
		String gotit = sb.toString();
		md5.reset();
		return gotit;
	}
}
